package com.oa.official.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.oa.official.common.utils.JwtHelper;
import com.oa.official.entity.system.SysUser;
import com.oa.official.mapper.SysUserMapper;
import com.oa.official.response.Result;
import com.oa.official.vo.wechat.BindPhoneVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;

@Slf4j
@Api(tags = "微信授权")
@Controller
@RequestMapping("/admin/wechat")
@CrossOrigin
public class WechatController {


    @Value(value = "wechat.userInfoUrl")
    private String userInfoUrl;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private WxMpService wxMpService;

    @ApiOperation(value = "微信回调的接口，我们为了获取OpenId")
    @GetMapping("/authorize")
    public String authorize(@RequestParam(value = "returnUrl")String returnUrl) throws UnsupportedEncodingException {
        //buildAuthorizationUrl()需要传递三个参数
        //1:第一个参数是进行授权的路径，那个路径中获取用户信息，我现在是userInfo
        //2:第二个是固定值，授权类型 WxConsts.OAuth2Scope.SNSAPI_USERINFO
        //3:第三个是但当你授权成功之后，跳转到的路径，吧“guiguoa”再转为“#”
        //返回一个回调地址
        String redirectUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(
                userInfoUrl,
                WxConsts.OAuth2Scope.SNSAPI_USERINFO,
                URLEncoder.encode(returnUrl.replace("guiguoa", "#"),"utf-8")
        );
        return "redirect:" + redirectUrl;
    }
    @ApiOperation(value = "微信回调的接口，我们为了获取OpenId")
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam(value = "code")String code,
                           @RequestParam(value = "state")String returnUrl) throws WxErrorException {
        //通过code获取accessToken
        WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        //再通过accessToken获取openId
        String openId = accessToken.getOpenId();
        log.info("获取的openId是:{}",openId);
        //还可以获取微信的用户信息
        WxOAuth2UserInfo wxOAuth2UserInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);
        log.info("微信的用户信息是:{}", JSON.toJSONString(wxOAuth2UserInfo));

        //根据openId查询用户表，看看是否存在这个用户
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getOpenId,openId);
        SysUser sysUser = sysUserMapper.selectOne(lambdaQueryWrapper);
        String token = "";
        if(Objects.nonNull(sysUser)){
            token = JwtHelper.createToken(sysUser.getId(),sysUser.getUsername());
        }
        if (!returnUrl.contains("?")){
            return "redirect:" + returnUrl + "?token" + token + "&openId=" + openId;
        }else {
            return "redirect:" + returnUrl + "&token" + token + "&openId=" + openId;
        }
    }


    @ApiOperation(value = "微信用户绑定手机号")
    @PostMapping("/bindPhone")
    @ResponseBody
    public Result bindPhone(@RequestBody BindPhoneVo bindPhoneVo){
        //根据手机号存在还是不存在
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getPhone,bindPhoneVo.getPhone());
        SysUser sysUser = sysUserMapper.selectOne(lambdaQueryWrapper);

        //如果手机号存在，那么更新openId
        if(Objects.nonNull(sysUser)){
            sysUser.setOpenId(bindPhoneVo.getOpenId());
            sysUserMapper.updateById(sysUser);
            String token = JwtHelper.createToken(sysUser.getId(),sysUser.getUsername());
            return Result.success(token);
        }
        return Result.error("手机号不存在,请联系管理员修改!");
    }
}
